﻿using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Web;
using System.Web.Services;

namespace TetriBricks.Web
{
    /// <summary>
    /// Summary description for ScoreService1
    /// </summary>
    [WebService(Namespace = "http://www.hosca.com/tetribricks")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
        // [System.Web.Script.Services.ScriptService]
    public class ScoreService : WebService
    {
        [WebMethod]
        public void GetLatestScores()
        {
            string filename = Path.Combine(Server.MapPath("~/App_Data/"), "highscores.json");
            HttpContext.Current.Response.WriteFile(filename);
        }

        [WebMethod]
        public void SaveScore(Score score)
        {
            List<Score> scores = ReadAll();
            scores.Add(score);
            SaveAll(scores);
        }

        private List<Score> ReadAll()
        {
            List<Score> listScores = null;
            string filename = Path.Combine(Server.MapPath("~/App_Data/"), "highscores.json");

            using (Stream tw = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Read))
            {
                var dcSerializer = new DataContractJsonSerializer(typeof (List<Score>));
                listScores = dcSerializer.ReadObject(tw) as List<Score>;
            }

            return listScores;
        }

        private void SaveAll(List<Score> scores)
        {
            string filename = Path.Combine(Server.MapPath("~/App_Data/"), "highscores.json");

            lock (this)
            {
                using (Stream tw = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    var dcSerializer = new DataContractJsonSerializer(scores.GetType());
                    dcSerializer.WriteObject(tw, scores);
                    tw.Flush();
                }
            }
        }
    }
}